package com.example.wechat;

import android.content.Context;
import android.media.MediaPlayer;
import android.util.Log;

import java.io.IOException;

public class VoicePlayer {
    private static final String TAG = "VoicePlayer";
    private MediaPlayer mediaPlayer;
    private boolean isPlaying = false;
    private String currentUrl;
    private final Context context;

    public interface PlaybackCallback {
        void onStart();
        void onComplete();
        void onError(String error);
    }

    public VoicePlayer(Context context) {
        this.context = context.getApplicationContext();
    }

    public void play(String url, PlaybackCallback callback) {
        if (isPlaying) {
            stop();
        }

        try {
            mediaPlayer = new MediaPlayer();
            mediaPlayer.setDataSource(url);
            mediaPlayer.setOnCompletionListener(mp -> {
                isPlaying = false;
                callback.onComplete();
            });
            mediaPlayer.setOnErrorListener((mp, what, extra) -> {
                isPlaying = false;
                callback.onError("播放失败: " + what);
                return true;
            });
            mediaPlayer.prepare();
            mediaPlayer.start();
            isPlaying = true;
            currentUrl = url;
            callback.onStart();
        } catch (IOException e) {
            Log.e(TAG, "播放失败", e);
            releasePlayer();
            callback.onError("播放失败: " + e.getMessage());
        }
    }

    public void stop() {
        if (mediaPlayer != null && isPlaying) {
            mediaPlayer.stop();
            isPlaying = false;
        }
    }

    public void pause() {
        if (mediaPlayer != null && isPlaying) {
            mediaPlayer.pause();
            isPlaying = false;
        }
    }

    public void resume() {
        if (mediaPlayer != null && !isPlaying) {
            mediaPlayer.start();
            isPlaying = true;
        }
    }

    public boolean isPlaying() {
        return isPlaying;
    }

    public String getCurrentUrl() {
        return currentUrl;
    }

    public void release() {
        stop();
        releasePlayer();
    }

    private void releasePlayer() {
        if (mediaPlayer != null) {
            mediaPlayer.release();
            mediaPlayer = null;
        }
    }
} 